package com.huilian.iotbox.admin.wap.controller;

import com.huilian.iotbox.admin.wap.aopLog.OperateLog;
import com.huilian.iotbox.admin.wap.service.UserService;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.controller.BaseController;
import com.huilian.iotbox.data.dto.UserDto;
import com.huilian.iotbox.data.dto.UserStoreDto;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.properties.SmsProperties;
import com.huilian.iotbox.data.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * @author 少凡
 * @date 2020/2/26 15:58
 */
@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private SmsProperties smsProperties;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @PostMapping("/sendSubscribe")
    public ServerResponse sendSubscribe(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        userDto.setUserId(userInfo.getId());
        return userService.sendSubscribe(userDto);
    }

    /**
     * 获取登用的用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/userInfo")
    public ServerResponse getUserInfo(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return ServerResponse.createBySuccess(userInfo);
    }

    /**
     * 获取最新用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/getNewUserInfo")
    public ServerResponse getNewUserInfo(HttpServletRequest request) {
        UserInfo userInfo = userService.getNewUserInfo(request);
        return ServerResponse.createBySuccess(userInfo);
    }

    /**
     * 发送验证码
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/smsCode")
    public ServerResponse smsCode(@RequestBody UserDto userDto, HttpServletRequest request) {
        return userService.smsCode(userDto, smsProperties.getKey());
    }

    /**
     * 注册
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public ServerResponse register(@RequestBody UserDto userDto) {
        return userService.register(userDto);
    }

    /**
     * 在小程序获取手机号注册（没验证码）
     *
     * @param userDto
     * @return
     */
    @PostMapping("/registerByAppletMobile")
    public ServerResponse registerByAppletMobile(@RequestBody UserDto userDto) {
        return userService.registerByAppletMobile(userDto);
    }

    /**
     * 绑定微信公众号登录
     *
     * @param userDto
     * @return
     */
    @PostMapping("/bindWeChatOfficialAccountLogin")
    public ServerResponse bindWeChatOfficialAccountLogin(@RequestBody UserDto userDto) {
        return userService.bindWeChatOfficialAccountLogin(userDto);
    }

    /**
     * 系统后台管理员
     *
     * @return
     */
    @GetMapping("/managers")
    public ServerResponse getListByAgencyId(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return userService.getListByAgencyId(userInfo);
    }


    /**
     * 修改用户
     *
     * @return
     */
    @PutMapping
    public ServerResponse update(@RequestBody User user) {
        return userService.update(user);
    }

    /**
     * 检查手机号和用户名是否存在
     *
     * @param mobile
     * @param username
     * @return
     */
    @GetMapping("/check")
    public ServerResponse checkIsExist(@RequestParam(required = false) String mobile,
                                       @RequestParam(required = false) String username) {
        return userService.checkIsExist(mobile, username);
    }


    @GetMapping("/findUserBalance")
    public ServerResponse findUserBalance(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return userService.findUserBalance(userInfo);
    }


    @OperateLog
    @PostMapping("/editUserRolePermission")
    public ServerResponse editUserRolePermission(@RequestBody UserStoreDto userStoreDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userStoreDto.setUserInfo(userInfo);
        return userService.editUserRolePermission(userStoreDto);
    }


    @GetMapping("/findSubAccountV2")
    public ServerResponse findSubAccountV2(HttpServletRequest request, User user) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        user.setUserInfo(userInfo);
        return userService.findSubAccountV2(user);
    }


    @PutMapping("/updateUserReceiptType")
    public ServerResponse updateUserReceiptType(HttpServletRequest request, @RequestBody UserDto userDto) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setId(userInfo.getId());
        Integer count = userService.updateUserReceiptType(userDto);
        if (count > 0) {
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("");
        }
    }

    @PutMapping("/updateUser")
    public ServerResponse updateUser(HttpServletRequest request, @RequestBody UserDto userDto) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        User user = new User();
        user.setId(userInfo.getId());
        user.setSignStatus(true);
        Integer count = userService.updateUser(user);
        if (count > 0) {
            String key = String.format(RedisKey.WAP_USERINFO, userInfo.getId());
            redisCacheTemplate.delete(key);
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("");
        }
    }

    @GetMapping("/findUserReceiptType")
    public ServerResponse findUserReceiptType(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return ServerResponse.createBySuccess(userService.findUserReceiptType(userInfo));
    }

    @PutMapping("/updatePwd")
    public ServerResponse updatePwd(HttpServletRequest request, @RequestBody UserDto userDto) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.updatePwd(userDto);
    }

    @PutMapping("/resetPwd")
    public ServerResponse resetPwd(HttpServletRequest request, @RequestBody UserDto userDto) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return userService.resetPwd(userDto);
    }

    @PutMapping("/updateOperatePassword")
    public ServerResponse updateOperatePassword(HttpServletRequest request, @RequestBody UserDto userDto) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.updateOperatePassword(userDto);
    }

    /**
     * 子账号注销
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/deleteSubAccountByUserIdV2")
    public ServerResponse deleteSubAccountByUserIdV2(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.deleteSubAccountByUserIdV2(userDto);
    }

    @PutMapping("/loginPwdReset")
    public ServerResponse loginPwdReset(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.loginPwdReset(userDto, request);
    }

    @PutMapping("/operatePwdReset")
    public ServerResponse operatePwdReset(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.operatePwdReset(userDto);
    }

    @GetMapping("/getResetSmsCode")
    public ServerResponse getSmsCode(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        UserDto userDto = new UserDto();
        userDto.setMobile(userInfo.getMobile());
        return userService.getResetSmsCode(userDto, smsProperties.getKey());
    }

    @PutMapping("/forgetOperate")
    public ServerResponse forgetOperate(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.forgetOperate(userDto);
    }

    /**
     * 找回密码
     *
     * @param userDto
     * @return
     */
    @PutMapping("/forgetLogin")
    public ServerResponse forgetLogin(@RequestBody UserDto userDto) {
        return userService.forgetLogin(userDto);
    }

    /**
     * 找回密码-获取验证码
     *
     * @param userDto
     * @return
     */
    @PostMapping("/getResetLoginSmsCode")
    public ServerResponse getResetLoginSmsCode(@RequestBody UserDto userDto) {
        return userService.getResetSmsCode(userDto, smsProperties.getKey());
    }

    @PutMapping("/updateOpenId")
    public ServerResponse updateOpenId(@RequestBody UserDto userDto) {
        return userService.updateOpenId(userDto);
    }


    /**
     * 检查手机号是否已注册账号并绑定微信，有注册没绑定微信就发短信验证码
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/checkAccountExistAndBindWx")
    public ServerResponse checkAccountExistAndBindWx(@RequestBody UserDto userDto, HttpServletRequest request) {
        return userService.checkAccountExistAndBindWx(userDto);
    }

    /**
     * 小程序绑定手机号
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/updateMobile")
    public ServerResponse updateMobile(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setId(userInfo.getId());
        userDto.setUserInfo(userInfo);
        return userService.updateMobile(userDto);
    }

    /**
     * 查询绑定手机号后的用户信息
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/findById")
    public ServerResponse findById(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.findById(userDto.getId());
    }

    /**
     * 获取当前用户的手机号和unionId
     */
    @GetMapping("/getMobileAndUnionId")
    public ServerResponse getMobileAndUnionId(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        User user = userService.getMobileAndUnionId(userInfo.getId());
        userInfo.setMobile(user.getMobile());
        userInfo.setUnionId(user.getUnionId());
        return ServerResponse.createBySuccess(userInfo);
    }


    /**
     * 解除手机号或者微信绑定
     */
    @PostMapping("/unbindMobileOrWeChat")
    public ServerResponse unbindMobileOrWeChat(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setId(userInfo.getId());
        return userService.unbindMobileOrWeChat(userDto);
    }

    /**
     * 修改unionId
     * 修改openId
     */
    @PostMapping("/updateUnionIdAndOpenId")
    public ServerResponse updateUnionIdAndOpenId(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        if (userDto.getId() == null) {
            userDto.setId(userInfo.getId());
        }
        return userService.updateUnionIdAndOpenId(userDto);
    }

    @PutMapping("/updateUserInfo")
    public ServerResponse updateUserInfo(@RequestBody UserDto userDto, HttpServletRequest request) throws Exception {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setId(userInfo.getId());
        userDto.setUserId(userInfo.getId());
        userDto.setUserInfo(userInfo);
        return userService.updateUserInfo(userDto);
    }

    @GetMapping("/findWhetherToOwnUnionId")
    public ServerResponse findWhetherToOwnUnionId(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        try {
            if (userInfo.getUnionId() == null) {
                return ServerResponse.createByErrorMessage("账户未绑定微信");
            } else {
                return ServerResponse.createBySuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
    }

    @GetMapping("/findWhetherToSetWechatNotification")
    public ServerResponse findWhetherToSetWechatNotification(HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        try {
            return userService.findWhetherToSetWechatNotification(userInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage(e.getMessage());
        }
    }

    @GetMapping("/findUserByMerchantStoreId")
    public ServerResponse findUserByMerchantStoreId(UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        userDto.setUserId(userInfo.getId());
        return userService.findUserByMerchantStoreId(userDto);
    }

    @PostMapping("/finOneUserAndRoleUserByUserId")
    public ServerResponse finOneUserAndRoleUserByUserId(@RequestBody UserDto userDto, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        userDto.setUserInfo(userInfo);
        return userService.finOneUserAndRoleUserByUserId(userDto);
    }

}
